document.addEventListener('DOMContentLoaded', () => {
    fetch('http://your_server_ip:6060/data')  // Replace with your backend URL
        .then(response => response.json())
        .then(data => {
            let time = parseFloat((data.gametime / 3600).toFixed(2));
            // Process battle status (clearance status)
            const clearanceStatus = data.clearancestatus.split(' ');
            const clearanceTime = data.clearancetime.split(' ');

            const battleStatusData = clearanceStatus.map((status, index) => {
                return status == '1' ? 2 : 1;
            });

            const battleStatusDataColor = clearanceStatus.map((status, index) => {
                return status == '1' ? 'rgb(234, 229, 164)' : 'rgb(185, 185, 185)';
            });

            // Update battle chart (clearance status chart)
            const ctxArea = document.getElementById('myBarChart_game').getContext('2d');
            new Chart(ctxArea, {
                type: 'bar',
                data: {
                    labels: ['第1关', '第2关', '第3关', '第4关'],
                    datasets: [{
                        label: '通关情况',
                        data: battleStatusData,
                        backgroundColor: battleStatusDataColor,
                        borderColor: 'rgb(0, 0, 0)',
                        borderWidth: 1.5
                    }]
                },
                options: {
                    scales: {
                        xAxes: [{
                            time: {
                                unit: '关卡'
                            },
                            gridLines: {
                                display: false
                            },
                            ticks: {
                                maxTicksLimit: 6
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                min: 0,
                                max: 3,
                                maxTicksLimit: 4
                            },
                            gridLines: {
                                display: true
                            }
                        }],
                    },
                    legend: {
                        display: true,
                        labels: {
                            generateLabels: function(chart) {
                                return [{
                                    text: '通关',
                                    fillStyle: 'rgb(234, 229, 164)',
                                    strokeStyle: 'rgb(0, 0, 0)',
                                    lineWidth: 1.5
                                }, {
                                    text: '未通关',
                                    fillStyle: 'rgb(185, 185, 185)',
                                    strokeStyle: 'rgb(0, 0, 0)',
                                    lineWidth: 1.5
                                }];
                            }
                        }
                    }
                }
            });

            // Update game time chart (clearance time chart)
            const gameTimeData = clearanceTime.map((time, index) => {
                return time !== '-1' ? parseInt(time) : 0;
            });

            const ctxBar = document.getElementById('myBarChart_time').getContext('2d');
            new Chart(ctxBar, {
                type: 'bar',
                data: {
                    labels: ['第1关', '第2关', '第3关', '第4关'],
                    datasets: [{
                        label: '通关时长',
                        data: gameTimeData,
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1.5
                    }]
                },
                options: {
                    scales: {
                        xAxes: [{
                            time: {
                                unit: '关卡'
                            },
                            gridLines: {
                                display: false
                            },
                            ticks: {
                                maxTicksLimit: 6
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                min: 0,
                            },
                            gridLines: {
                                display: true
                            }
                        }],
                    },
                    legend: {
                        display: true
                    }
                }
            });

            AddTable(data);  // 添加武器数据到表格
            initDataTable();  // 初始化 DataTable
            alert('你已经游玩了 ' + time + ' 小时!  请注意休息！');
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });

    async function AddTable(data) {
        // Update weapon table
        const weaponNames = data.weapons.split(',');
        const weaponLevels = data.weapon_levels.split(',');

        // 确保 tbody 元素存在
        const weaponTableBody = document.querySelector('#DataTable tbody');
        weaponNames.forEach((weapon, index) => {
            const row = document.createElement('tr');

            // 创建序号列
            const cell1 = document.createElement('td');
            cell1.textContent = index + 1;  // 显示序号
            // 创建武器名称列
            const cell2 = document.createElement('td');
            cell2.textContent = weapon;
            // 创建武器等级列
            const cell3 = document.createElement('td');
            cell3.textContent = weaponLevels[index];

            row.appendChild(cell1);  // 添加序号列
            row.appendChild(cell2);  // 添加武器名称列
            row.appendChild(cell3);  // 添加武器等级列

            weaponTableBody.appendChild(row);  // 将行添加到表格
        });
    }

    // 3) DataTable 初始化，必须放在 renderTable 之后、且只调用一次
    function initDataTable() {
        const tableEl = document.getElementById('DataTable');
        if (!tableEl) {
            console.error('Table element not found!');
            return;  // 如果表格元素不存在，退出
        }
        if (tableEl._dataTable) {
            tableEl._dataTable.destroy();
        }
        tableEl._dataTable = new simpleDatatables.DataTable(tableEl, {
            perPageSelect: [16, 24, 32, 40, 48],
            perPage: 16,
            layout: {
                top: '{select}{search}',   // 确保把下拉放到搜索框左侧
                bottom: '{info}{pager}'
            },
            labels: {
                placeholder: "搜索 …",
                perPage: "{select} 条/页",
                noRows: "没有找到数据",
                info: "显示 {start} 到 {end}，共 {rows} 条"
            }
        });

        // 确保表头居中
        const headers = tableEl.querySelectorAll('th');
        headers.forEach(header => {
            header.style.textAlign = 'center';
        });
    }
});
